//多线程版本
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>//提供地址转换函数
#include<pthread.h>
//信息结构体
struct SockInfo
{
    struct sockaddr_in addr;
    int fd;
};
struct SockInfo infos[512];
void* working(void* arg);
int main()
{
    //1.创建监听的套接字
    int fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd == -1)
    {
        perror("socket error!");
        return -1;
    }
    //2.绑定本地的IP和端口号
    struct sockaddr_in address;//声明一个sockaddr_in结构体变量address，用于存储服务器地址信息 
    address.sin_family = AF_INET;//地址族为IPV4
    address.sin_port = htons(9999);//htons用于将主机字节序转换为网络字节序
    address.sin_addr.s_addr = INADDR_ANY;//监听所有网络接口
    int ret = bind(fd,(struct sockaddr*)&address,sizeof(address));
    if(ret == -1)
    {
        perror("bind error!");
        return -1;
    }
    //3.监听
    ret = listen(fd,128);
    if(ret == -1)
    {
        perror("listen error!");
        return -1;
    }
    //初始化结构体数组
    int max = sizeof(infos)/sizeof(infos[0]);
    for(int i = 0;i < max; i++)
    {
        bzero(&infos[i],sizeof(infos[1]));
        infos[i].fd = -1;
    }
    //4.阻塞并等待客户端连接
    int addrlen = sizeof(struct sockaddr_in);
    while(1)
    {
        struct SockInfo* pinfo;
        for(int i = 0;i < max; i++)
        {
            if(infos[i].fd == -1)
            {
                pinfo = &infos[i];
                break;
            }
        }
        int cfd = accept(fd,(struct sockaddr*)&pinfo->addr,(socklen_t*)&addrlen);
        pinfo->fd = cfd;
        if(cfd == -1)
        {
            perror("accept error!");
            break;
        }
        //创建子线程
        pthread_t tid;
        pthread_create(&tid,NULL,working,pinfo);
        pthread_detach(tid);        
    }
    close(fd);
    return 0;
}
void* working(void* arg)
{
    struct SockInfo* pinfo = (struct SockInfo*)arg;
    //连接建立成功，打印客户端的IP和端口号信息
    char ip[32];
    printf("客户端的IP:%s,端口:%d\n",inet_ntop(AF_INET,&pinfo->addr.sin_addr.s_addr,ip,sizeof(ip)),
    ntohs(pinfo->addr.sin_port));//inet_ntop将大端的整数型，转换为小端的点分十进制IP地址
    //5.通信
    while(1)
    {
        //接受数据
        char buff[1024];
        int len = recv(pinfo->fd,buff,sizeof(buff),0);
        if(len > 0)
        {
            printf("client say : %s\n",buff);
            send(pinfo->fd,buff,len,0);
        }
        else if(len == 0)
        {
            printf("客户端已经断开了连接...\n");
            break;
        }
        else
        {
            perror("recv error!");
            break;
        }
    }
    //6.关闭文件描述符
    close(pinfo->fd);
    pinfo->fd = -1;
    return NULL;
}